<template>
  <div class="search">
    <van-search
      v-model="SearchText"
      shape="round"
      background="#dfe7e3"
      placeholder="请输入搜索关键词"
      @search="onSearch"
    />
  </div>
  <van-divider
    :style="{ color: '#1989fa', borderColor: '#1989fa', padding: '0 16px' }"
  >
    已选标签
  </van-divider>
  <van-space wrap>
    <!-- activeIds.splice(activeIds.indexOf(tag), 1)"
     activeIds.indexOf(tag)  这个参数表示在找点击的标签的索引下面，从这个索引下标开始删除
     1  表示删除的数量
    -->
    <van-tag
      v-for="tag in activeIds"
      :key="tag"
      closeable
      size="medium"
      type="primary"
      @close="activeIds.splice(activeIds.indexOf(tag), 1)"
    >
      {{ tag }}
    </van-tag>
  </van-space>
  <van-divider
    :style="{ color: '#1989fa', borderColor: '#1989fa', padding: '0 16px' }"
  >
    搜索选项
  </van-divider>
  <van-tree-select
    v-model:active-id="activeIds"
    v-model:main-active-index="activeIndex"
    :items="items"
  />
</template>

<script setup lang="ts">
import { ref } from 'vue'

const SearchText = ref('')

const activeIds = ref(['杭州'])
const activeIndex = ref(0)
// 原始数组
const originItems = [
  {
    text: '浙江',
    children: [
      { text: '杭州', id: '杭州' },
      { text: '温州', id: '温州' },
      { text: '宁波', id: '宁波' },
      { text: 'test1', id: 'test1' },
      { text: 'test2', id: 'test2' },
    ],
  },
  {
    text: '江苏',
    children: [
      { text: '南京', id: '南京' },
      { text: '无锡', id: '无锡' },
      { text: '徐州', id: '徐州' },
    ],
  },
]
const items = ref(originItems)
const onSearch = (val: string) => {
  //过滤出originItems中children中text包含val的项
  const newItems = originItems.map(item => {
    const newItem = { ...item }
    newItem.children = item.children.filter(child => child.text.includes(val))
    return newItem
  })
  if (!activeIds.value.includes(val) && val) {
    activeIds.value.push(val)
  }
  items.value = newItems
}
</script>

<style scoped></style>
